<template>
  <div class="business-device">
    <!-- left -->
    <div class="fl">
      <ShopListMenu title="组织架构" @emitShopId="emitShopId" />
    </div>
    <!-- right -->
    <div v-if="shopId" class="right app-main-content-box">
      <div class="flexRBC top">
        <div class="title">{{ curSelectLabel }}</div>
        <div>
          <el-button
            v-if="
              business.syncTmpMerchantId &&
                !$store.getters.banBtnList.includes('BTN_PRINTER_ADD')
            "
            type="primary"
            size="medium"
            round
            @click="handleSync"
          >同步打印机
          </el-button>
          <el-button
            v-if="
              !business.syncTmpMerchantId &&
                !$store.getters.banBtnList.includes('BTN_PRINTER_ADD')
            "
            type="primary"
            size="medium"
            round
            @click="handleAdd"
          >新增打印机
          </el-button>
        </div>
      </div>
      <!-- 搜索 -->
      <div class="list-search">
        <el-input
          v-model="filterForm[searchSelect]"
          placeholder="请输入内容"
          class="input-with-select"
          @keyup.enter.native="searchByKeyword"
        >
          <el-select slot="prepend" v-model="searchSelect" placeholder="请选择">
            <el-option
              v-for="item in selectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-input>
        <el-button
          :loading="searchLoading"
          type="primary"
          size="medium"
          round
          icon="el-icon-search"
          @click="searchByKeyword"
        >查 询
        </el-button>
      </div>

      <!-- 表格 -->
      <div class="table">
        <el-table
          v-loading="tableLoading"
          :data="list"
          size="medium"
          border
          empty-text="暂无数据"
        >
          <el-table-column prop="name" fixed="left" label="打印机名称" />
          <el-table-column prop="brandType" label="品牌">
            <template slot-scope="scope">
              <span>{{ brandOptions[scope.row.brandType] }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="modelNo" label="型号" />
          <el-table-column prop="snCode" label="SN号" />
          <el-table-column label="所在门店">
            <template>
              <span>{{ shopName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template slot-scope="scope">
              <span
                :class="
                  scope.row.status === 1
                    ? 'app-text-color-success'
                    : 'app-text-color-danger'
                "
              >{{ scope.row.status === 1 ? "启用中" : "已停用" }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="tag" label="备注" />
          <el-table-column label="操作" fixed="right" width="160">
            <template slot-scope="scope">
              <el-button
                v-if="!$store.getters.banBtnList.includes('BTN_PRINTER_EDIT')"
                type="text"
                size="small"
                @click="handleEdit(scope.row)"
              >编辑
              </el-button>
              <el-button
                v-if="
                  !$store.getters.banBtnList.includes(
                    'BTN_PRINTER_STATUS_MANAGE'
                  )
                "
                type="text"
                size="small"
                @click="handleStatus(scope.row)"
              >{{ scope.row.status === 2 ? "启用" : "停用" }}
              </el-button>
              <el-button
                v-if="
                  !business.syncTmpMerchantId &&
                    !$store.getters.banBtnList.includes('BTN_PRINTER_DELETE')
                "
                type="text"
                size="small"
                @click="handleDel(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <pagination-direction
        v-if="paginationConfig.total"
        :config="paginationConfig"
        @sizeschange="sizesChange"
        @pagechange="pageChange"
      />
    </div>

    <div v-else class="right app-main-content-box">
      <div class="empty-tips">配置打印机需先创建门店</div>
    </div>

    <!-- 新增编辑弹框 -->
    <dialog-printer ref="dialogPrinter" :shop-id="shopId" :business="business" />
  </div>
</template>

<script>
import { listPrinter, delPrinter, editPrinter } from '@/api/printer'
import DialogPrinter from './components/DialogPrinter'
import DialogLookStyle from './components/DialogLookStyle'
import { syncManagePrinter } from '@/api/business'

export default {
  components: {
    DialogPrinter,
    DialogLookStyle
  },
  props: {
    business: {},
    tabName: {
      type: String,
      require: true
    }
  },
  data() {
    return {
      // 配置
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      selectOptions: [
        {
          value: 'name',
          label: '打印机名称'
        }
      ],
      brandOptions: {
        1001: '飞鹅',
        2001: '易联云',
        3001: '博实结'
      },
      searchSelect: 'name', // 搜索的类型
      // 状态
      tableLoading: false, // 表格loading
      searchLoading: false, // 表格loading
      // 数据
      list: [],
      curSelectLabel: '打印机',
      total: 0,
      shopId: 0,
      shopName: '',
      // 筛选数据
      filterForm: {
        name: '',
        shopId: ''
      }
    }
  },
  watch: {
    tabName(val) {
      if (val === 'printer') {
        this.fetchData()
      }
    },
    searchSelect(val) {
      this.filterForm.name = ''
    }
  },
  mounted() {},
  methods: {
    /**
     * 获取数据
     */
    // 获取数据
    fetchData(
      pageNum = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      if (!this.filterForm.shopId) {
        return
      }
      // 加入page
      this.filterForm.pageNum = pageNum
      this.filterForm.pageSize = pageSize
      const params = Object.assign({}, this.filterForm)
      // 清除多余字段
      for (const key in params) {
        if (params[key] === '' || params[key] === 'all') {
          delete params[key]
        }
      }
      this.tableLoading = true
      listPrinter(params)
        .then((res) => {
          if (res.code === 0) {
            this.list = res.data
          }
        })
        .catch(() => {})
        .finally(() => {
          this.tableLoading = false
          this.searchLoading = false
        })
    },

    // 分页sizes改变
    sizesChange(pageSize) {
      this.fetchData()
    },

    // 分页page改变
    pageChange(page) {
      this.fetchData()
    },

    /**
     * 按钮组
     */
    // 选择门店
    emitShopId(item) {
      this.shopId = item.shopId
      this.shopName = item.shopName
      this.curSelectLabel = item.shopName
      this.filterForm.shopId = item.shopId
      this.filterForm.name = ''
      this.fetchData(1)
    },

    // 点击搜索
    searchByKeyword() {
      this.searchLoading = true
      this.fetchData(1)
    },

    // 同步
    async handleSync() {
      if (!this.shopId) return
      const res = await syncManagePrinter({
        shopId: this.shopId
      })
      const { msg } = res
      if (msg === 'success') {
        this.$message.success('同步成功')
        this.fetchData()
      }
    },

    // 新增
    handleAdd() {
      this.$refs.dialogPrinter.openAdd().then(() => {
        this.fetchData()
      })
    },

    // 编辑
    handleEdit(row) {
      this.$refs.dialogPrinter.openEdit(row).then(() => {
        this.fetchData()
      })
    },

    // 删除
    handleDel(row) {
      this.$confirm(`确定删除打印机 ：${row.name} ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        roundButton: true
      }).then(() => {
        const params = {}
        params.shopId = row.shopId
        params.printerId = row.id
        this.tableLoading = true
        delPrinter(params)
          .then((res) => {
            if (res.code === 0) {
              this.fetchData()
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
            } else {
              this.$message.error(res.msg)
            }
          })
          .catch(() => {})
          .finally(() => {
            this.tableLoading = false
          })
      })
    },

    // 停用 启用
    handleStatus(row) {
      const type = row.status === 2 ? '启用' : '停用'
      this.$confirm(`确定${type}打印机 ${row.name} ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        roundButton: true
      })
        .then(() => {
          const params = Object.assign({}, row)
          params.status = row.status === 2 ? 1 : 2
          this.tableLoading = true
          editPrinter(params)
            .then((res) => {
              if (res.code === 0) {
                row.status = params.status
                this.$notify({
                  title: '成功',
                  message: `已${type}`,
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
              } else {
                this.$message.error(res.msg)
              }
            })
            .catch(() => {})
            .finally(() => {
              this.tableLoading = false
            })
        })
        .catch(() => {})
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/* 右侧表格 */
.right {
  overflow: hidden;

  .top {
    margin-bottom: 10px;

    .title {
      font-size: 18px;
      font-weight: bold;
    }
  }

  /* 搜索*/
  .list-search {
    padding-top: 10px;
    margin-bottom: 10px;

    .el-select {
      width: 120px;
    }

    .el-input {
      width: 400px;
      margin-right: 10px;
    }
  }
  .empty-tips {
    padding: 100px 0;
    font-size: 14px;
    text-align: center;
    color: #606266;
  }
}
</style>
